<?php
namespace App\Services;

use Illuminate\Support\Facades\DB;
use App\Models\StoreOrder;
use App\Services\BaseConfigService;
use App\Services\StoreGoodsService;
use App\Services\StoreCartService;
use App\Services\CouponListService;
use App\Services\CouponSendService;
class StoreOrderService extends CommonService{
	
	
	/**
	 * 添加订单
	 */
	function addOrder($userInfo,$gids,$counts,$cgids='',$message='',$coupon_code = ''){
		$storeGoodsService = new StoreGoodsService();
		try{
			$gidsArr = explode(',',$gids);
			$countsArr = explode(',',$counts);
			$goods_list = [];
			$real_price = 0;
			for($i = 0 ;$i < count($gidsArr);$i++){
				$goodsResult = $storeGoodsService->findInfo(array('id'=>$gidsArr[$i]));
				$real_price += $goodsResult['data']['price'] * $countsArr[$i];
				
				$goods['gid'] = $goodsResult['data']['id'];
				$goods['goods_title']= $goodsResult['data']['title'];
				$goods['goods_count'] = $counts[$i];
				$goods['goods_img'] = $goodsResult['data']['img_url'];
				$goods['goods_price'] = $goodsResult['data']['price'];
				array_push($goods_list, $goods);
			}
			
			$min = 0;
			if($coupon_code){//使用优惠码
				$couponSendService = new CouponSendService();
				$couponListService = new CouponListService();
				
				$couponListResult = $couponListService->findInfo(array('coupon_code'=>$coupon_code));
				if($couponListResult['code'] != 1){
					return $this->show(0,'优惠码不存在');
				}else{
					$nowDate = date('Y-m-d');
					if($nowDate > $couponListResult['data']['end_time']){
						return $this->show(0,'优惠码已过期');
					}elseif($couponListResult['data']['is_use'] == 1){
						return $this->show(0,'优惠码已使用');
					}else{
						$row = array(
							'openId'=>$userInfo['openId'],
							'nickName'=>$userInfo['nickName'],
							'coupon_code'=>$coupon_code,
							'money'=>$couponListResult['data']['money']
						);
						$result = $couponSendService->addInfo($row);
						if($result['code'] == 1){
							$min = $couponListResult['data']['money'];
							$couponListService->updateInfo(array('coupon_code'=>$coupon_code),array('is_use'=>1));
						}
					}
				}
				
			}
			
			$addRow = array(
				'order_num'=>$this->getOrderNum(),
				'real_price'=>$real_price,
				'total_price'=>$real_price - $min,
				'coupon_code'=>$coupon_code,
				'goods_list'=>json_encode($goods_list),
				'openId'=>$userInfo['openId'],
				'nickName'=>$userInfo['nickName'],
				'avatarUrl'=>$userInfo['avatarUrl'],
				'created_at'=>date('Y-m-d H:i:s'),
				'updated_at'=>date('Y-m-d H:i:s'),
			);
			
			$result = DB::table('store_order')->insertGetId($addRow);
		
			if($result){
				
				if($cgids){
					$storeCartService = new StoreCartService();
					$cgids = implode(',',$cgids);
					$storeCartService->deleteInfo(null,'id',$cgids);
				}
				return $this->show(1,'插入成功',$result);
			}
			return $this->show(0,'插入失败','');
		}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
	}
	
	/**
	 * 生成订单号
	 */
	function getOrderNum(){
		$date = date('Ymd');
		$baseConfigService = new BaseConfigService();
		$config = $baseConfigService->findConfigKeyValue('order_prefix');
		$serialNumber =  mt_rand(10000000,99999999);
		
		
		return $config['data'] . $date. $serialNumber;
	}
	
	/**
	 * 前台分页查询
	 */
	function paginateOrder($where = null,$page = 1,$pagesize =10){
		$skip = ($page - 1) * $pagesize;
		try{
			$result = StoreOrder::where($where)
		 				->skip($skip)
		 				->take($pagesize)
		 				->get();
		 	$count = StoreOrder::where($where)->count();		
		 	if(count($result) != 0){
            	return $this->show(1,'查询成功',['data'=>$result,'count'=>$count]);
            }else{
            	return $this->show(0,'查询失败',$result);
            }
		}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
	}
	
	
	/**
	 * 分页查询
	 * where([
    *			['status', '=', '1'],
    *			['subscribed', '<>', '1'],
    *	])
	 */
    function paginateInfo($where = null,$limit = 10){
    	try{
    		$result = StoreOrder::where($where)
    					->latest()
            			->paginate($limit);
           
            if(count($result) != 0){
            	return $this->show(1,'查询成功',$result);
            }else{
            	return $this->show(0,'查询失败',$result);
            }
    	}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
    		
    }
    
    
   
    /**
     * 添加管理员
     */
    function addInfo($param = array()){
    	try{
    	
    		$model = new StoreOrder();
    		foreach($param as $key => $value) {
                $model->$key = $value;
            }
          
            $result = $model->save();
            if($result){
            	return $this->show(1,'添加成功',$result);
            }else{
            	return $this->show(0,'添加失败',$result);
            }
    	}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
    }
    
    /**
     * 更新管理员
     */
    function updateInfo($where = null,$param=[]){
    	try{
    		$result = StoreOrder::where($where)->update($param);
    		
            if($result){
            	return $this->show(1,'更新成功',$result);
            }else{
            	return $this->show(0,'更新失败',$result);
            }
    	}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
    	
    	
    }
    
    
    /**
     * 查询单条管理员
     */
    function findInfo($where = null){
    	try{
    		$result = StoreOrder::where($where)->first();
            if($result){
            	return $this->show(1,'查询成功',$result);
            }else{
            	return $this->show(0,'查询失败',$result);
            }
    	}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
    }
    
    
    /**
     *查询所有用户
     */
    function findAllInfo($where = null){
    	try{
    		$result = StoreOrder::where($where)->orderBy('sort', 'asc')->latest()->get();
            if($result){
            	return $this->show(1,'查询成功',$result);
            }else{
            	return $this->show(0,'查询失败',$result);
            }
    	}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}	
    }
    
    /**
     * 删除
     */
    function deleteInfo($where = null){
    	try{
    		$result = StoreOrder::where($where)->delete();
            if($result){
            	return $this->show(1,'删除成功',$result);
            }else{
            	return $this->show(0,'删除失败',$result);
            }
    	}catch(\Exception $e){
    		return $this->show(2,'系统错误',$e);
    	}
    }
    
}
